import os
from pymongo import MongoClient
from flask import (Flask, request, session, g, redirect, url_for, abort,
     render_template, flash,json)
from pypinyin import lazy_pinyin

from flask_limiter import Limiter
from flask_limiter.util import get_remote_address


app = Flask(__name__)
app.debug = True

limiter = Limiter(
    app,
    key_func=get_remote_address,
    global_limits=["20000 per day", "5000 per hour"]
)

@app.route('/')
@app.route('/index')
@limiter.exempt
def index():
    return render_template('index.html')

@app.route('/city/<name>')
@limiter.exempt
def city(name=None):
    pinyin = ''.join(lazy_pinyin(name))
    if name=='陕西':
        pinyin+='1'
    return render_template('city.html',genjson=pinyin,cityname=name)

@app.route('/tables')
@limiter.exempt
def tables():
    collection = getCollection('Data')
    proName = request.args.get('province')
    cityName = request.args.get('cityName')
    page = request.args.get('page')
    if not page:
        page=1
    else:
        page=int(page)
    sum = collection.find({'来源':{'$regex':proName},'数据':{'$regex':cityName[0:2]}}).count()
    if page>sum/17:
        page=int(sum/17)
    pages = getPages(page,sum)
    data = []
    try:
        for each in  collection.find({'来源':{'$regex':proName},'数据':{'$regex':cityName[0:2]}},{'表名':1,'id':1,'_id':0})[17*page-17:17*page]:
            data.append(each)
        return render_template('tables.html',cityName=cityName,province=proName,data=data,page=page,pages=pages)
    except:
        return '没有找到数据'

@app.route('/table')
@limiter.limit("5000/day;400/hour;10/minute")
def gettable():
    id = request.args.get('id')
    cityName = request.args.get('cityName')
    collection = getCollection('Data')
    data = collection.find_one({'id':int(id)})
    table = data['数据']
    flag=-1
    if len(cityName)>2:
        cityName=cityName[0:2]
    del(data['数据'])
    muliTable = handleMulitTable(table)
    if muliTable:
        table = muliTable
        for lis in muliTable:
            v = lis[1]
            for i in range(len(v[0])):
                if cityName in v[0][i]:
                    flag=i
                    break
            break
        table.sort()
        return render_template('table_mult.html',Data = data,Table=table,cityName=cityName,flag=flag)
    else:
        lines = table.split('@')
        table=[]
        for line in lines:
            table.append(line.split('|'))
        for i in range(len(table[0])):
            if cityName in table[0][i]:
                flag=i
                break
        return render_template('table.html',Data = data,Table=table,cityName=cityName,flag=flag)

def getPages(page,sum):
    if sum<10:
        return [i for i in range(1,sum)]
    if page<5:
        return [i for i in range(1,10)]
    if sum-page<5:
        return [i for i in range(sum-9,sum)]
    return [i for i in range(page-4,page+4)]

def getCollection(collectionName):
    client = MongoClient('192.168.0.220', 27017)
    db = client['tjdb']
    collection = db[collectionName]
    return collection

def handleMulitTable(str):
    '''
    处理一表多年数据
    '''
    if '〒' in str:
        years = str.split('〒')[0].split('|')
        datas = str.split('〒')[1]
        yearh = len(years)
        datas = [each for each in datas.split('@')]
        newdata = []
        for each in datas:
            newdata.append(each.split('|'))
        # print(newdata)
        lisline = []
        column = []
        danwei = []
        for line in newdata:
            if line[2]=='s':
                lisline.append(line[0])
            if line[2]=='s'and line[3]=='1':
                if not line[1]:
                    danwei.append('单位')
                else:
                    danwei.append(line[1])
            if line[2]=='i' and line[3]=='1':
                column.append(line[0])
                danwei.append(line[1])
        tables = []
        for i in range(yearh):
            tables.append([])
            tables[i].append([])
            tables[i].append([])
            tables[i][0]=years[i]
            tables[i][1]=[]
        for i in range(yearh):
            table=tables[i][1]
            t = ['分组']
            t.extend(column)
            table.append(t)
            table.append(danwei)
            for line in newdata:
                if line[2] =='s':
                    t=[line[0]]
                    table.append(t)
                else:
                    t.append(line[i+6])
        return tables
    return
if __name__ == '__main__':

    app.run(host='0.0.0.0',port=5000)
